#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:洪卫
 

import os,sys
import serial
import time
import json
import timetool
import threading
from sys import version_info  

def pythonVersion():
    return version_info.major

key1 = 1
key2 = 2

dtime = 0.040
tcount = 5
tdelay = 0.1

# 创建一个锁对象
lock = threading.Lock()


def getTime():
    global dtime,tdelay,tcount
    f = open('timer.txt','r')
    dat = f.read()
    f.close()
    configs = json.loads(dat)
    ttime = int(timetool.conventTimeFromStrConfig(configs['time'])*1000)
    dtime = float(configs['tdtime']/1000.0)
    tcount = configs['tCount']
    tdelay = float(configs['delay']/1000.0)
    print('time1:%s'%(configs['time']))
    print(ttime,dtime,tcount)
    return ttime




serialT = None

def readPort():
    global serialT
    time.sleep(0.003)
    n = serialT.inWaiting()
    # print(n)
    if n > 0:
        pstr = serialT.read(n)
        if pythonVersion() == 2:
            # return pstr
            print('setial read:%s'%(pstr))
        else:
            # return str(pstr)
            print('setial read:%s'%(str(pstr)))

log = []

def sendCmd(pcmd):
    global serialT,log
    back = None
    lock.acquire()  # 获取锁
    try:
        back = serialT.write(pcmd.encode())
        serialT.flush()
        log.append(pcmd)
    finally:
        lock.release()  # 释放锁
    
    # print('send cmd,:%s,isOk:%s'%(pcmd,str(back)))
    return back

#'@'工作模式字典
type2Pins = {1:['0','1'],2:['2','3'],3:['4','5'],4:['6','7'],5:['8','9'],6:['a','b'],7:['c','d'],8:['e','f'],9:['g','h'],10:['i','j'],11:['k','l'],12:['m','n'],13:['o','p'],14:['q','r'],15:['s','t'],16:['u','v']}
# 1: 1, 2, 3     
# 2: 4, 5, 6
# 3: 7, 8, 9
# 4: 10,11,12
# 5: 13,14,15

# type2Pins = {1:['<0000>','<FFFF>'],2:['<0000>','<FFFF>']}


def delaylog(n):
    for i in range(n):
        print('after %ds well exit.'%(n-i))


tlist = {
    #    [1和2间隔时间   2,3间隔时间      3号6次间隔时间     按下时间     ]
            1:[0.8,         0.03,            0.03,         0.05],
            2:[0.8,         0.03,            0.03,         0.05],
            3:[0.8,         0.03,            0.03,         0.05],
            4:[0.8,         0.03,            0.03,         0.05],
            5:[0.8,         0.03,            0.03,         0.05]
        }

def touchPin(tid,n):
    n += (tid-1)*3
    sendCmd(type2Pins[n][0])
    time.sleep(tlist[tid][3])
    sendCmd(type2Pins[n][1])
    time.sleep(tlist[tid][2])

def task(tid):
    # print("task start id:",tid)
    # time.sleep(1)  # 模拟工作耗时
    # print("task end id:",tid)
    print('tid =',tid)
    touchPin(tid,1)   #1号按下
    time.sleep(tlist[tid][0])  #间隔时间0.8秒
    touchPin(tid,2)   #2号按一下
    time.sleep(tlist[tid][1])  #间隔时间0.8秒
    for i in range(6): #3号6次
        touchPin(tid,3)

def run(tid):
    thread = threading.Thread(target=task, args=(tid,))
    thread.start()
    return thread

def main():
    global serialT,tdelay,tcount
    f = open('config.txt','r')
    jstr = f.read()
    f.close()
    jdic = json.loads(jstr)
    t = serial.Serial(jdic['port'],jdic['btv'],timeout=0.5)
    serialT = t
    time.sleep(2)
    sendCmd('@')
    readPort()

    sendCmd('<FFFF>')

    ttime = getTime()
    if not (key1 and key2 and ttime):
        print('init timer erro,and exit...')
        return
    isRuned = False
    threads = []
    while True:
        time.sleep(0.001) #进行一个延时,防止占用CPU过高
        nowtime = int(time.time()*1000)
        if ttime <= nowtime:
            if not isRuned and ttime <= nowtime:
                threads.append(run(1))  #第1组，J1,J2,J3启动
                time.sleep(0.001)       #第1组和第2组启动间隔时间
                threads.append(run(2))  #第2组，J4,J5,J6启动
                time.sleep(0.001)       #第2组和第3组启动间隔时间
                threads.append(run(3))  #第3组，J7,J8,J9启动
                time.sleep(0.001)       #第3组和第4组启动间隔时间
                threads.append(run(4))  #第4组，J10,J11,J12启动
                time.sleep(0.001)       #第4组和第5组启动间隔时间
                threads.append(run(5))  #第5组，J13,J14,J15启动
                isRuned = True
                for thread in threads:  #等待所有操作完成
                    thread.join()
                print(log)
            isRuned = True
        elif isRuned: #定时器已经运行
            print('run end ...')
            delaylog(10)
            
def test():
    run(1)
    time.sleep(0.1)
    run(3)
    time.sleep(0.1)
    time.sleep(3)
if __name__ == '__main__':
    main()
    # test()
